<template>
  <div class="page-container">
    <!-- 步骤条开始 -->
    <steps :stepList="stepList" />
    <!-- 步骤条结束 -->
    <!-- 订单基础信息 -->
    <page-form :model="form" ref="formRef" :rules="rules" layout="vertical" v-show="stepList[0].active">
      <card title="客户信息">
        <a-alert class="a-alert">
          <template #icon>
            <icon-exclamation-circle />
          </template>
          <div class="alert-item">如承租人姓名或联系电话有误需要修改，请到个人会员中修改，或创建完成后，在订单编辑页中进行修改</div>
        </a-alert>
        <customer />
      </card>
      <card title="租赁信息">
        <lease @calcPriceFn="calcPriceFn" @timeRangeChange="timeRangeChange" />
      </card>
      <card title="订单排车">
        <platoon />
      </card>
      <!-- 合同信息 -->
      <contract-card :showDivider="false" />
    </page-form>
    <!-- 订单费用信息 -->
    <div v-show="stepList[1].active">
      <order-fee-pane ref="orderFeePaneRef" />
      <!-- 账单分期计划 -->
      <page-form :model="form" :rules="rules" layout="vertical">
        <order-payment-pane v-if="feeRealtimeSum > 0" :contractAmount="feeRealtimeSum" />
      </page-form>
    </div>
  </div>
  <!-- 底部 footer -->
  <page-form-footer hideCancel hideOk>
    <template v-if="stepList[0].active">
      <a-button @click="cancelFn">关闭</a-button>
      <a-button type="primary" :disabled="!nextStepIsValid" @click="stepClickFn(stepList[1])">下一步</a-button>
    </template>
    <template v-if="stepList[1].active">
      <a-button @click="stepClickFn(stepList[0])">上一步</a-button>
      <a-button type="primary" :loading="okLoading" @click="submitFn">确认</a-button>
    </template>
  </page-form-footer>
  <!-- 排车周期校验 -->
  <PlatoonCarCheckModal ref="platoonCarCheckModalRef" />
</template>

<script setup name="LongOrderForm">
  import { ref, reactive, watch, provide, computed, nextTick, inject } from 'vue'
  // 组件
  import customer from './components/customer.vue'
  import lease from './components/lease.vue'
  import platoon from './components/platoon.vue'
  import steps from '../components/steps.vue'
  import contractCard from '../components/contract/contract-card.vue'
  import orderFeePane from './components/order-fee-pane.vue'
  import { Notification, Message } from '@arco-design/web-vue'
  import { computeRentDay, createOrder, calcPrice } from '@/api/order/czsOrder'
  import orderPaymentPane from '../components/order-payment-pane.vue'
  import { getFeeSum } from '../components/order-fee/fee-statistic'
  // ---------------------------
  import { usePageDict } from '@/hooks/useDict'
  import dayjs from 'dayjs'
  import { cloneDeep } from 'lodash-es'
  import useNavigate from '@/hooks/useNavigate'
  import useUserStore from '@/store/modules/user'

  const userStore = useUserStore()
  console.log(userStore, 'userStore')
  const { navigateBack, navigateClose } = useNavigate()
  const dict = usePageDict('longOrderDict')
  provide('dict', dict)
  const scrollbarRef = inject('scrollbarRef')
  // 滚动到顶部
  const scrollTopFn = () => {
    scrollbarRef && scrollbarRef.value.scrollTop(0)
  }
  // 租赁周期限制最小时长 1个月
  const timeRangeValidator = async (value, callback) => {
    if (value) {
      let start = value[0]
      let end = value[1]
      if (start && end) {
        const param = {
          expectedUseCarTime: dayjs(start).format('YYYY-MM-DD 00:00:00'),
          expectedReturnCarTime: dayjs(end).format('YYYY-MM-DD 23:59:59'),
        }
        let res = await computeRentDay(param)
        if (res.result.months < 1) {
          callback('租赁周期最短时间范围为1个月')
        }
      } else {
        callback('请选择预计租赁周期')
      }
    }
    callback()
  }
  // 表单规则
  const rules = reactive({
    memberType: { required: true, message: '请选择客户类型' },
    memberPhone: [
      { required: true, message: '请输入联系电话' },
      {
        minLength: 11,
        match: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
        message: '仅支持数字，长度11位',
      },
    ],
    memberName: { required: true, message: '请输入承租人' },
    cardNumber: { match: /^[a-zA-Z0-9]+$/, message: '支持数字、英文，最多18个字符' },
    clientId: { required: true, message: '请选择客户公司名称' },
    siteId: { required: true, message: '请选择取车门店' },
    orderSource: { required: true, message: '请选择订单来源' },
    timeRange: [{ required: true, message: '请选择预计租赁周期' }, { validator: timeRangeValidator }],
  })

  // 表单对象
  const defaultStartTime = dayjs().format('YYYY-MM-DD 00:00:00')
  const form = ref({
    paymentScheme: 2, // 默认分支
    paymentMethod: 2, // 默认月付
    lnstalmentFirstDate: dayjs(new Date()).format('YYYY-MM-DD'),
    memberType: 2, // 客户类型
    cardType: 0, // 证件类型，默认身份证
    orderSource: 1, // 订单来源
    carSource: 1, // 车辆来源
    timeRange: [defaultStartTime],
    expectedUseCarTime: defaultStartTime,
    contractList: [
      {
        contractFileId: '',
        contractNo: '',
        contractType: 1,
        contractTypeName: '租赁合同',
        contractName: '',
        id: 1,
        refId: '',
        status: 'edit',
      },
    ],
  })
  provide('form', form)
  // formRef
  const formRef = ref()
  provide('formRef', formRef)

  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1, // 线下、线上费用需要根据选的是渠道订单还是线下订单处理
        feeDetailList: [],
        feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee', 'depositFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  // 实时费用信息开始
  const feeRealtimeSum = computed(() => {
    let orderFee = feeForm.value.orderFee
    if (orderFee) {
      return getFeeSum(orderFee)
    }
    return 0
  })
  // 更改
  watch(
    () => form.value.paymentScheme,
    (newVal) => {
      if (newVal == 2) {
        rules.paymentMethod = { required: true, message: '请选择收款方式' }
        rules.lnstalmentFirstDate = { required: true, message: '请选择首期付款日' }
      } else {
        rules.paymentMethod = {}
        rules.lnstalmentFirstDate = {}
      }
    }
  )
  // 步骤条数据
  const stepList = ref([
    { stepText: '订单信息', stepNum: 1, active: true },
    { stepText: '费用信息', stepNum: 2, active: false },
  ])

  // 返回事件
  const cancelFn = () => {
    navigateClose()
  }
  // 确认事件
  const okLoading = ref(false)
  const orderFeePaneRef = ref()
  const submitFn = () => {
    // 获取费用信息
    orderFeePaneRef.value.getCostInfo((costInfo) => {
      let orderFee = feeForm.value.orderFee
      console.log(form.value, 'orderFee')

      let param = {
        ...form.value,
        ...costInfo,
        orderFee: costInfo.orderFee[0],
        sendServiceFlag: form.value.sendServiceFlag ? 1 : 0,
        returnServiceFlag: form.value.returnServiceFlag ? 1 : 0,
        contractAmount: getFeeSum(orderFee),
      }
      // 快速连续点击下一步至确定按钮时，费用未及时回显报错，加上限制
      if (param.orderFee && param.orderFee.feeDetailList.length == 0) {
        return
      }
      // 合同-信息
      let contractList = form.value.contractList
      param.contractFileId = contractList[0].contractFileId
      param.contractNo = contractList[0].contractNo
      param.contractName = contractList[0].contractName

      // 默认值
      param.channelType = 0
      // 删除部分冗余字段
      delete param.rentDays
      delete param.timeRange
      if (form.value.emergencyContactPhone == '') {
        param.emergencyContactPhone = null
      }
      // 开启 loading
      okLoading.value = true
      createOrder(param)
        .then(() => {
          Notification.success({
            content: '保存成功',
            closable: true,
            duration: 3000,
          })
          navigateBack()
        })
        .finally(() => {
          // 结束 loading
          okLoading.value = false
        })
    })
  }
  // 下一步是否可点击
  const nextStepIsValid = computed(() => {
    // 需要判断必填项是否均填写
    let formValue = form.value
    let requiredProp = ['memberName', 'siteId', 'timeRange']
    // 个人客户
    if (formValue.memberType == 2) {
      requiredProp.push('memberPhone')
    }
    // 企业客户
    if (formValue.memberType == 1) {
      requiredProp.push('clientId')
    }
    // 合同信息
    if (formValue.contractList?.length > 0) {
      let contract = formValue.contractList[0]
      if (contract.fileId) {
        if (!contract.contractNo) {
          return false
        }
      }
    }
    return !requiredProp.some((item) => {
      const value = formValue[item]
      if (item == 'timeRange') {
        // 时间范围：开始时间和结束时间需要都有值
        if (item && item.length) {
          if (value[0] && value[1]) {
            return !(value[0] && value[1])
          } else {
            return true
          }
        }
      } else {
        return !value
      }
    })
  })
  // form 聚焦部分字段是否发生变化
  const isChangeFormByProps = (propStrList, prevForm) => {
    let formVal = form.value
    return propStrList.some((prop) => formVal[prop] != prevForm[prop])
  }

  // 点击第二步、第一步事件
  // 读取门店模板配置，初始化 feeForm
  let prevForm = {}
  const stepClickFn = (step) => {
    console.log(form.value, 'console.log(form.value);')
    if (!step.active) {
      let step1 = stepList.value[0]
      let step2 = stepList.value[1]
      // 切换到第二步
      if (step.stepNum == 2) {
        // 可能出现手机号格式不正确
        formRef.value.validate((error) => {
          if (!error) {
            let formValue = form.value
            if (
              isChangeFormByProps(
                [
                  'siteId',
                  'originalModelId',
                  'returnSiteId',
                  'startTime',
                  'endTime',
                  'sendServiceFlag',
                  'longitude',
                  'latitude',
                  'returnServiceFlag',
                  'returnLongitude',
                  'returnLatitude',
                ],
                prevForm
              )
            ) {
              const param = {
                modelId: formValue.originalModelId,
                siteId: formValue.siteId,
                returnSiteId: formValue.returnSiteId,
                startTime: dayjs(formValue.timeRange[0]).format('YYYY-MM-DD 00:00:00'),
                endTime: dayjs(formValue.timeRange[1]).format('YYYY-MM-DD 23:59:59'),
                sendServiceFlag: formValue.sendServiceFlag ? 1 : 0,
                longitude: formValue.longitude,
                latitude: formValue.latitude,
                returnServiceFlag: formValue.returnServiceFlag ? 1 : 0,
                returnLongitude: formValue.returnLongitude,
                returnLatitude: formValue.returnLatitude,
                type: 1, // 固定值
              }
              calcPrice(param).then((res) => {
                if (res.result) {
                  step1.active = false
                  step2.active = true
                  scrollTopFn()
                  nextTick(() => {
                    orderFeePaneRef.value.initStoreTemplate(prevForm, res.result).then(() => {
                      prevForm = cloneDeep({
                        ...form.value,
                      })
                    })
                  })
                }
              })
            } else {
              step1.active = false
              step2.active = true
              scrollTopFn()
              nextTick(() => {
                orderFeePaneRef.value.initStoreTemplate(prevForm).then(() => {
                  prevForm = cloneDeep({
                    ...form.value,
                  })
                })
              })
            }
          }
        })
      } else {
        step1.active = true
        step2.active = false
        scrollTopFn()
      }
    }
  }
  const calcPriceFn = () => {
    if (form.value.originalModelId) {
      let formValue = form.value
      const param = {
        modelId: formValue.originalModelId,
        siteId: formValue.siteId,
        returnSiteId: formValue.returnSiteId,
        startTime: dayjs(formValue.timeRange[0]).format('YYYY-MM-DD 00:00:00'),
        endTime: dayjs(formValue.timeRange[1]).format('YYYY-MM-DD 23:59:59'),
        sendServiceFlag: formValue.sendServiceFlag ? 1 : 0,
        longitude: formValue.longitude,
        latitude: formValue.latitude,
        returnServiceFlag: formValue.returnServiceFlag ? 1 : 0,
        returnLongitude: formValue.returnLongitude,
        returnLatitude: formValue.returnLatitude,
        type: 1, // 固定值
      }
      calcPrice(param).then((res) => {
        if (res.result) {
          nextTick(() => {
            orderFeePaneRef.value.initStoreTemplate(prevForm, res.result).then(() => {
              prevForm = cloneDeep({
                ...form.value,
              })
            })
          })
        }
      })
    }
  }

  // 占用周期判断
  const platoonCarCheckModalRef = ref()
  const timeRangeChange = (val) => {
    platoonCarCheckModalRef.value.confirm({
      title: '预计租赁周期变更，不影响租车费及账单计划分期，请到订单详情-费用信息页面修改费用及账单分期，请确认是否修改预计租赁周期？',
      required: true,
      params: {
        refId: form.value.id,
        startTime: val[0] + ' 00:00:00',
        endTime: val[1] + ' 23:59:59',
        useType: 3,
        carId: form.value.carId,
      },
      onCancel: () => {
        form.value.expectedUseCarTime = defaultStartTime
        form.value.expectedReturnCarTime = undefined
        form.value.timeRange = [defaultStartTime]
        form.value.rentDays = undefined
        form.value.leaseNumberStr = undefined
      },
    })
  }
</script>

<style lang="less" scoped>
  :deep(body) {
    background: red;
    // height: 80px !important;
  }
  .contContainer {
    margin-top: 25px;
    .item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
  }

  .a-alert {
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
    margin-bottom: 20px;
  }
</style>
